const sendPost = {
    sendData: { filePath: '' },
    taskConfig: { taskStatus: false },
    saveFilePath: [],
    saveFileList: 0,
    setting: {},
    watchValue(key, newVal) {
        if (key == 'taskStatus' && newVal) {
            //当前回复任务已全部完成
            if (sendPost.saveFilePath.length) {
                sendPost.saveFilePath.forEach((item) => {
                    files.remove(item)
                })
                sendPost.saveFilePath = []
            }
            console.log('sendLinke', sendPost.taskConfig.sendLinke);

            Xhs.taskConfig.taskStatus = true
        }
        if (key == 'errorTask' && newVal) {
            let params = {
                taskType: 'send_post',
                taskName: '发帖',
                errorTip: newVal,
                taskData: sendPost.sendData,
                taskDate: Comman.getDate()
            }
            Xhs.errorTask(params)
            sendPost.taskConfig.taskStatus = true
        }
    },
    init(data) {
        sendPost.sendData = data;
        sendPost.setting = data.setting || {}
        sendPost.taskConfig = Comman.defineReactive(
            {
                taskStatus: false,
                errorTask: '',
                sendLinke: ''
            },
            '',
            sendPost.watchValue
        )
        if (data.setting.image || data.setting.video) {
            sendPost.resolveMiddle(data.setting)
        }
        sendPost.openTask()
    },
    start(data) {
        //初始化数据
        sendPost.init(data)
    },
    openTask() {
        let homeMnue = btnConfig.home.homeMnue
        //重置首页
        while (!depth(homeMnue.options.depth).id(homeMnue.options.id).exists()) {
            back();
            console.log('back...');
            sleep(2000);
        }
        //打开发帖页面
        let openBtn = btnConfig.home.homePostBtn.default()
        if (!openBtn) {
            console.log('回复任务：消息按钮控件获取失败');
            sendPost.taskConfig.errorTask = '回复任务：消息按钮控件获取失败'
            return
        }
        if (openBtn.bounds) {
            App.clickByBtn(openBtn, true)
        } else {
            App.click(btnConfig.home.homeMessageBtn.position.x, btnConfig.home.homeMessageBtn.position.y, true)
        }
        let tip = text('不再提醒').findOne(2000)
        if (tip) {
            App.clickByBtn(tip, 2)
        }
        sleep(1000)
        if (!sendPost.saveFileList) {
            console.log('发帖任务：报错---文件缓存失败或无文件配置');
            sendPost.taskConfig.errorTask = '文件缓存失败或无文件配置'
            return
        }
        sendPost.chooseFile()

    },
    resolveMiddle(seed) {
        console.log('FUNCTION: resolveMiddle');
        let resource = []
        if (seed.image) {
            resource = seed.image.split(',')
        }
        if (seed.video) {
            resource = [seed.video]
        }
        sleep(2000)
        if (resource.length) {
            // myUi.setTopText(Comman.getDate() + ': 发帖任务：' + "资源准备中....")
            let num = 0
            resource.forEach((item, index) => {
                let urlName = item.split('/').slice(-1)[0]
                if (!urlName) {
                    console.log('回复任务：文件解析名称失败：' + item);
                    return
                }
                let filePath = Xhs.resourcePath + new Date().getTime() + '_' + urlName
                let fileStatus = files.createWithDirs(filePath)
                let response = http.get(item);
                if (response.statusCode == 200) {
                    let fileBytes = response.body.bytes();
                    files.writeBytes(filePath, fileBytes);
                    media.scanFile(filePath);
                    sendPost.saveFilePath.push(filePath)
                    num += 1
                    console.log('回复任务：文件下载完成：' + item + ' ---------NO：' + index);
                } else {
                    console.log('回复任务：文件解析名称失败' + response.statusCode);
                }
                sleep(500)
            })
            sendPost.saveFileList = num
        }
        sleep(1000)
    },
    chooseFile() {
        // 等待文件选择界面加载完成
        let messageFileMenu = btnConfig.file.messageFileMenu.default()
        if (!messageFileMenu) {
            console.log('发帖任务：报错---找不到文件列表');
            sendPost.taskConfig.errorTask = '找不到文件列表'
            return
        }
        // 选择文件
        let fileItem = btnConfig.file.messageFileImgRadio.default()
        if (!fileItem.length) {
            console.log('发帖任务：报错---找不到文件选中按钮');
            sendPost.taskConfig.errorTask = '找不到文件选中按钮'
            return
        }
        //遍历对应资源，选中它
        fileItem.forEach((file, index) => {
            if (index < sendPost.saveFileList) {
                App.clickByBtn(file, 2)
            }
        })

        let stepBtn = btnConfig.file.FileRadioNext.default()
        if (!stepBtn) {
            console.log('发帖任务：报错---找不到编辑下一步');
            sendPost.taskConfig.errorTask = '找不到编辑下一步'
            return
        }
        if (stepBtn.bounds) {
            App.clickByBtn(stepBtn, 3)
        } else {
            App.click(btnConfig.file.FileRadioNext.position.x, btnConfig.file.FileRadioNext.position.y, 3)
        }

        let stepBtn2 = btnConfig.file.FileEditNext.default()
        if (!stepBtn2) {
            console.log('发帖任务：报错---找不到编辑下一步');
            sendPost.taskConfig.errorTask = '找不到编辑下一步'
            return
        }
        if (stepBtn2.bounds) {
            App.clickByBtn(stepBtn2, 3)
        } else {
            App.click(btnConfig.file.FileEditNext.position.x, btnConfig.file.FileEditNext.position.y, 3)
        }
        sendPost.setText()
    },
    setText() {
        let cancleBtn = btnConfig.system.cancleBtn.default()
        if (cancleBtn) {
            App.clickByBtn(cancleBtn, 3)
        }
        let setting = sendPost.setting
        //标题输入框
        let titleDom = btnConfig.postEdit.postTitle.default()
        if (!titleDom) {
            console.log('发帖任务：报错---找不到标题输入框');
            sendPost.taskConfig.errorTask = '找不到标题输入框'
            return
        }
        titleDom.setText(setting.title)
        App.randomSleep(2, 5)

        //正文输入框
        let contentDom = btnConfig.postEdit.postContent.default() || btnConfig.postEdit.postVideoContent.default()
        if (!contentDom) {
            console.log('发帖任务：报错---找不到正文输入框');
            sendPost.taskConfig.errorTask = '找不到正文输入框'
            return
        }
        contentDom.setText(setting.content)
        //话题输入框
        setClip('')
        sleep(1000)
        if (setting.topic) {
            let str = setting.topic.split(',').reduce((pre, next) => {
                return pre + '#' + next + ' '
            }, '')
            setClip(str)
        }
        sleep(1000)
        contentDom.paste()
        App.randomSleep(2, 5)

        let sendBtn = btnConfig.postEdit.postSendBtn.default()
        if (!sendBtn) {
            console.log('发帖任务：报错---找不到发布按钮');
            sendPost.taskConfig.errorTask = '找不到发布按钮'
            return
        }
        if (sendBtn.bounds) {
            App.clickByBtn(sendBtn, true)
        } else {
            App.click(btnConfig.postEdit.postSendBtn.position.x, btnConfig.postEdit.postSendBtn.position.y, true)
        }
        let num = 0
        let flage = true
        while (!textContains('发布成功').exists()) {
            console.log('等待发布成功');
            if (num >= 10) {
                flage = false
                break;
            }
            num++
            sleep(1500)
        }
        sleep(2000)
        if (!flage) {
            console.log('发帖任务：找不到笔记成功标记');
            sendPost.taskConfig.taskStatus = true
        } else {
            sendPost.getLinks(setting.title)
        }
    },
    getLinks() {
        let nowSendArticle = btnConfig.postEdit.postSendTitle.default() || btnConfig.postEdit.postSendView.default()
        if (!nowSendArticle) {
            console.log('发帖任务：报错---找不到帖子发布成功界面');
            sendPost.taskConfig.errorTask = '找不到帖子发布成功界面'
            return
        }
        if (nowSendArticle.bounds) {
            App.clickByBtn(nowSendArticle, true)
        } else {
            App.click(btnConfig.postEdit.postSendView.position.x, btnConfig.postEdit.postSendView.position.y, true)
        }

        let moreBtn = btnConfig.post.moreBtn.default() || btnConfig.post.moreVideoBtn.default() || btnConfig.post.shareBrn.default()
        if (!moreBtn) {
            console.log('发帖任务：报错--- 找不到更多');
            sendPost.taskConfig.taskStatus = '找不到更多'
            return
        }
        if (moreBtn.bounds) {
            App.clickByBtn(moreBtn, true)
        } else {
            App.click(btnConfig.post.moreBtn.position.x, btnConfig.post.moreBtn.position.y, true)
        }


        let copyBtn = btnConfig.post.copyBtn.default()
        let moreBtnMenu = btnConfig.post.moreBtnMenu.default()
        if (!moreBtnMenu) {
            console.log('发帖任务：报错--- 找不到moreBtnMenu');
            sendPost.taskConfig.errorTask = '找不到moreBtnMenu'
            return
        }
        if (!copyBtn) {
            let scroll = true
            while (!copyBtn && scroll) {
                scroll = moreBtnMenu.scrollForward()
                sleep(2000)
                copyBtn = btnConfig.post.copyBtn.default()
                sleep(2000)
            }
            if (!copyBtn) {
                console.log('发帖任务：报错--- 找不到复制链接按钮');
                sendPost.taskConfig.errorTask = '找不到复制链接按钮'
                return
            }
        }

        if (copyBtn.bounds) {
            App.clickByBtn(copyBtn, true)
        } else {
            App.click(btnConfig.post.copyBtn.position.x, btnConfig.post.copyBtn.position.y, true)
        }

        // launch(Xhs.AppPackName)
        // sleep(1000)
        // sendPost.taskConfig.sendLinke = getClip() || '查询文章链接失败，请手动查询'
        // sleep(3000)
        // launch(Xhs.packName);
        let resolveInputBtn = btnConfig.post.resolveInputBtn.default()
        if (resolveInputBtn) {
            App.clickByBtn(resolveInputBtn, 3)
            let input = btnConfig.post.resolveInput.default() || btnConfig.post.resolveInput2.default()
            if (input) {
                input.paste()
                App.randomSleep(2, 4)
                input = btnConfig.post.resolveInput.default() || btnConfig.post.resolveInput2.default()
                sendPost.taskConfig.sendLinke = input ? input.text() : '查询文章链接失败，请手动复制帖子链接到帖子链接处'
                setText('')
                App.randomSleep(2, 4)
                back()
            }
            sleep(2000)
        } else {
            console.log('找不到输入框');
        }
        App.randomSleep(2, 4)
        back()
        sleep(2000)
        sendPost.taskConfig.taskStatus = true
    }
}
module.exports = sendPost